﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.Xna.Framework.Graphics;
using ProjectMercury;

namespace Orion.Lib
{
    public class LevelFlowManager
    {
        public List<dynamic> Frames = new List<dynamic>();
        string levelname = "";
        int levelindex = 0;

        public Texture2D BackgroundImage;
        public  List<ParticleEffect> ParicleEffects = new List<ParticleEffect>();


        public LevelFlowManager(XDocument _levelFile)
        {
            //Load main level information
            levelname = _levelFile.Root.Attribute("name").Value;
            var ind = _levelFile.Root.Attribute("index").Value;
            levelindex = int.Parse(string.IsNullOrEmpty(ind)?"0":ind);

            var bi = _levelFile.Root.Element("BackgroundImage");
            if(bi != null)
            {
                BackgroundImage = MyGame.staticContent.Load<Texture2D>("..\\" + bi.Attribute("root").Value + "\\" + bi.Value);
            }

            //effects
            var ef = _levelFile.Root.Element("ParicleEffects");
            if (ef != null)
            {
                var effect = MyGame.staticContent.Load<ParticleEffect>("..\\" + bi.Attribute("root").Value + "\\" + ef.Value);
                effect.Initialise();
                effect.LoadContent(MyGame.staticContent);
                ParicleEffects.Add(effect);
            }


            //Load frames
            var tt = from frames in _levelFile.Root.Element("Frames").Elements() select frames;
            foreach (var item in tt)
            {
               Frames.Add(CreateDynamicFrame(item));
            }
            Frames = Frames.OrderBy(frame => frame.Time).ToList<dynamic>();
        }

        private dynamic CreateDynamicFrame(XElement item)
        {
           dynamic frame = 
               new
               {
                   SourceXml = item,
                   Action = Activator.CreateInstance(
                   item.Element("Action").Attribute("assambly").Value, 
                   item.Element("Action").Attribute("class").Value).Unwrap(),
                   Parameters = item.Element("Action").Attributes(),
                   Time =  TimeSpan.Parse(item.Attribute("Time").Value)
               };
           return frame;
        }

        public void RegisterTrigger(ITrigger trigger)
        {
            
        }
    }

}
